<template>
  <div>
    <div>
      <span>欢迎来到添加作业模块</span>
      <el-divider></el-divider>
    </div>
    <div class="tab">
      <span>作业名称:</span>
      <el-input placeholder="请输入作业名称" clearable v-model="taskName"></el-input>
    </div>

    <el-table
      ref="multipleTable"
      :data="questionList"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="题号">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <!-- 该属性设为单行显示 -->
      <el-table-column prop="details" label="题目" show-overflow-tooltip></el-table-column>
      <el-table-column prop="teacherName" label="发布人"></el-table-column>
    </el-table>
    <div class="btn">
      <el-button @click="submit()" class="two" type="primary">发布</el-button>
      <el-button @click="toggleSelection()" type="info" class="two">取消</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      questionList: [],
      multipleSelection: [],
      tid: this.$store.state.userId,
      taskName: '',
      str: ''
    }
  },

  created() {
    this.getQuestionList()
  },

  methods: {
    // 获得所有题目
    async getQuestionList() {
      const { data: res } = await this.$http.get(
        'user/question/getQuestionList'
      )
      if (res.code !== 200) return this.$message.error('获取题目列表失败')

      this.questionList = res.data

      // 少了题目的时间
    },

    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },

    // 发布
    async submit() {
      if (this.taskName == '') {
        return this.$message.error('请填入考试名称！')
      }
      if (this.multipleSelection.length == 0) {
        return this.$message.error('请勾选题目！')
      }
      console.log(this.multipleSelection)
      this.str = this.multipleSelection.join(',')
      const { data: res } = await this.$http.post(
        `exam/addExam?ids=${this.str}&teacherId=${this.tid}&examTest=0&name=${this.taskName}`
      )
      if (res.code !== 200) return this.$message.error('获取题目列表失败')
      this.$message.success('成功')
    },

    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = []
      for (var i = 0; i < val.length; i++) {
        this.multipleSelection.push(val[i].id)
      }
      console.log(this.multipleSelection)
    }
  }
}
</script>

<style lang="less" scoped>
.tab {
  span {
    white-space: nowrap;
    margin-top: 10px;
    margin-right: 20px;
    margin-left: 10px;
  }
  display: flex;
}
.btn {
  margin-left: 80px;
  margin-top: 120px;
}

.two {
  margin-left: 40px !important;
  width: 150px;
}
</style>